<template>
  <Card>
    <Space direction="vertical">
      <ProjectTab @change="onChangeProject" />
      <Space>
        <Button shape="circle" type="primary" @click="onCreate" :disabled="!project.id">
          <IconPlus />
        </Button>
      </Space>
      <Api ref="apiRef" :input="{ projectId: project.id }" inputWatch :load="() => listByProjectId(project.id)" v-slot="{ output }" type="Array" :immediate="false">
        <Table :data="output" size="mini" :load="loadMore" :page="false">
          <TableColumn title="名称" field="name">
            <template #cell="{ row }">
              <Popover position="right">
                <Button :text="row.name" isText />
                <template #content>
                  <Space>
                    <Button text="编辑" />
                    <Button text="创建子节点" @click="onCreateChild(row)" />
                    <Button text="删除" v-if="row.isLeaf" />
                  </Space>
                </template>
              </Popover>
            </template>
          </TableColumn>
          <TableColumn title="Key" field="data.key" />
          <TableColumn title="备注" field="data.remark" />
          <TableColumn title="排序" field="sort" />
          <TableColumn title="创建日期" :width="170" field="createdAt" type="Datetime" />
          <TableColumn title="更新日期" :width="170" field="updatedAt" type="Datetime" />
        </Table>
      </Api>
    </Space>
  </Card>
</template>

<script setup lang="ts">
import { Button, Card, Popover, Space, Table, TableColumn } from '@idmy/ui'
import { IconPlus } from '@idmy/ui-icon'
import ProjectTab from '@/components/sys/Project/tab/index.vue'
import { Api } from '@idmy/core'
import { listByProjectId } from '@/components/rbac/Permission/tree/services'

const PermissionCreate = defineAsyncComponent(() => import('../create/index.vue'))
const PermissionChildCreate = defineAsyncComponent(() => import('../create/ChildCreate.vue'))

const rows = ref([])

const apiRef = ref()
const load = () => apiRef.value.onLoad()

const project = ref({})
const onChangeProject = val => {
  project.value = val
  load()
}

const loadMore = async ({ id }, done) => {
  // const data = await listDescendants(id)
  //done(data)
}

const onCreate = model =>
  Modal.open({
    component: PermissionCreate,
    title: model?.id ? '修改权限' : '创建权限',
    width: 2,
    enableLock: true,
    props: {
      model,
    },
    onClose: isOk => isOk && load(),
  })

const onCreateChild = parent =>
  Modal.open({
    component: PermissionChildCreate,
    title: '创建子节点权限',
    enableLock: true,
    width: 2,
    props: {
      parent,
    },
    onClose: isOk => isOk && load(),
  })
</script>
